package com.quanshu.change.login.view;

import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;
import com.quanshu.change.login.entity.CountryFlagEntity;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.LoginInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.CountDownTimerUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.gui.login.DialogCountryList;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.base.view.BaseTitleBar;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ResetPasswordByPhoneActivity extends BaseActivity {

    @BindView(R.id.reset_pwd_title)
    BaseTitleBar resetPwdTitle;
    @BindView(R.id.icon_area)
    ImageView iconArea;
    @BindView(R.id.area_show)
    TextView areaShow;
    @BindView(R.id.area_select)
    LinearLayout areaSelect;
    @BindView(R.id.reset_pwd_title_txt)
    EditText resetPwdTitleTxt;
    @BindView(R.id.send_message_button)
    TextView sendMessageButton;
    @BindView(R.id.reset_pwd_get_code)
    FrameLayout resetPwdGetCode;
    @BindView(R.id.reset_pwd_input_code)
    EditText resetPwdInputCode;
    @BindView(R.id.reset_pwd_cl)
    ConstraintLayout resetPwdCl;
    @BindView(R.id.alter_pwd)
    TextView alterPwd;
    @BindView(R.id.tips_true)
    TextView tipsTrue;
    @BindView(R.id.tips_false)
    TextView tipsFalse;
    @BindView(R.id.tips_true1)
    TextView tipsTrue1;
    @BindView(R.id.tips_false1)
    TextView tipsFalse1;
    private CountryFlagEntity countryFlagEntity;
    private List<CountryFlagEntity> countryInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password_by_phone);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        ImmersionBar.with(this).titleBar(resetPwdTitle).statusBarColor("#ffffff").statusBarDarkFont(true).init();
        resetPwdTitle.setLeftImage(R.drawable.icon_back_black_2_0).setCenterText("重置登录密码").setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
            @Override
            public void onclickLeft() {
                finish();
            }

            @Override
            public void onclickRight() {

            }
        });
        getCountryFlag();
        RxViewHelper.getInstance().clicks(areaSelect, aVoid -> doGetCountries());
        RxViewHelper.getInstance().clicks(resetPwdGetCode, aVoid -> doSendSms());
        RxViewHelper.getInstance().clicks(alterPwd, aVoid -> {
            if (countryFlagEntity != null) {
                resetPwd();
            }
        });
        resetPwdTitleTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() < 11) {
                    tipsTrue.setVisibility(View.INVISIBLE);
                    tipsFalse.setVisibility(View.VISIBLE);
                } else {
                    tipsTrue.setVisibility(View.VISIBLE);
                    tipsFalse.setVisibility(View.INVISIBLE);
                }
                if (s.length() == 11 && resetPwdInputCode.getText().length() >= 4) {
                    alterPwd.setEnabled(true);
                } else {
                    alterPwd.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        resetPwdInputCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() < 4) {
                    tipsTrue1.setVisibility(View.INVISIBLE);
                    tipsFalse1.setVisibility(View.VISIBLE);
                } else {
                    tipsTrue1.setVisibility(View.VISIBLE);
                    tipsFalse1.setVisibility(View.INVISIBLE);
                }
                if (s.length() >= 4 && resetPwdTitleTxt.getText().length() == 11) {
                    alterPwd.setEnabled(true);
                } else {
                    alterPwd.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void doGetCountries() {
        if (countryInfos != null && countryInfos.size() > 0) {
            doShowCountriesDialog();
        } else {
            getCountryFlag();
            if (countryInfos != null && countryInfos.size() > 0) {
                doShowCountriesDialog();
            }
        }
    }

    private void doShowCountriesDialog() {
        DialogCountryList dialogCountryList = new DialogCountryList(this);
        dialogCountryList.show();
        dialogCountryList.setData(countryInfos);
        dialogCountryList.getItemClickSubject().subscribe(tmpCountryInfo -> {
            dialogCountryList.dismiss();
            countryFlagEntity = tmpCountryInfo;
            areaShow.setText(tmpCountryInfo.getCountry_name());
            Glide.with(this).load(Config.URL_HOST_SHOP + countryFlagEntity.getCountry_img()).into(iconArea);
        });
    }

    private void getCountryFlag() {
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .getCountryList("")
                .compose(new BaseTransformer<>(this))
                .subscribe(response -> {
                    Log.d("获取国旗数据", "doGetCountries: " + response.getData().toString());
//                        countryInfos = AppUtils.formatData(response.getData());
                    countryInfos = response.getData();
                    if (countryInfos != null && countryInfos.size() > 0) {
                        for (int a = 0; a < countryInfos.size(); a++) {
                            if (Integer.valueOf(countryInfos.get(a).getId()) == 1) {
                                countryFlagEntity = countryInfos.get(a);
                            }
                        }
                    }

                });
    }

    /**
     * 发送短信验证码
     */
    private void doSendSms() {
        if (TextUtils.isEmpty(resetPwdTitleTxt.getText()) && !CheckUtil.checkTelNumRule(resetPwdTitleTxt.getText().toString())) {
            ToastHelper.toast("手机号格式不正确");
            return;
        }
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .doSendSms(AppUtils.getSignParams(resetPwdTitleTxt.getText().toString()), countryFlagEntity.getZone_description()+resetPwdTitleTxt.getText().toString())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast("发送成功！");
                        CountDownTimerUtils timerUtils = new CountDownTimerUtils(sendMessageButton, 60000, 1000);
                        timerUtils.start();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    /**
     * 重置登录密码
     */

    private void resetPwd() {
        NetClient.getInstance()
                .getShopService(LoginInterface.class)
                .alterLoginPwd(AppUtils.getSignParams(countryFlagEntity.getZone_description() + resetPwdTitleTxt.getText().toString(), resetPwdInputCode.getText().toString()), countryFlagEntity.getZone_description() + resetPwdTitleTxt.getText().toString(), resetPwdInputCode.getText().toString())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        Bundle bundle = new Bundle();
                        bundle.putInt(ResetPasswordSuccessfulActivity.TIPS_SHOW, 1);
                        BaseTool.goActivity(ResetPasswordByPhoneActivity.this, ResetPasswordSuccessfulActivity.class, bundle);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }
}
